import { useEffect, useState } from 'react';
import { Space, Switch, Table, message, Popconfirm, Input, Select, Button } from 'antd';
import type { TableProps } from 'antd';
import Hoc_login from "@/utils/Hoc_login"
import { getGroup, delGroup, updateGroup } from '@/api';
import city from "@/data/city.json"

function Index() {

  // 团购数据
  const [data, setData] = useState([])
  // 搜索框数据
  const [searchVal, setSearchVal] = useState("")
  // 状态数据
  const [statusVal, setStatusVal] = useState("")
  // 三级联动数据
  const [provinceData, setProvinceData] = useState(city)
  const [cityData, setCityData] = useState(city[0].children)
  const [cityItem, setCityItem] = useState(city[0].children[0].code)
  const [areaData, setAreaData] = useState(cityData[0].children)
  const [areaItem, setAreaItem] = useState(cityData[0].children[0].code)
  const [wen, setWen] = useState("")

  useEffect(() => {
    (
      async (data: any) => {
        let res = await getGroup(data)
        let groupData = res.data.data.data
        groupData.map((item: any) => {
          item.key = item.group_id
          return item
        })
        setData(groupData)
      }
    )(data)
  }, [])


  // 状态选择
  const handleChange = (value: any) => {
    // console.log(value)
    setStatusVal(value)
    if (value === "请选择") {
      setStatusVal("")
    }
    if (value == "请选择") {
      getGroup(data).then((res: any) => {
        setData(res.data.data.data.map((item: any) => {
          item.key = item.group_id
          return item
        }))
      })
    }
  };

  // 三级联动事件
  const handleProvinceChange = (value: any) => {
    const index = provinceData.findIndex((item) => { return item.code == value })
    setCityData(city[index].children)
    setCityItem(city[index].children[0].code)
    setAreaData(city[index].children[0].children)
    setAreaItem(city[index].children[0].children[0].name)
    setWen(city[index].children[0].children[0].name)
    if (value === "00") {
      setWen("")
    }
    if (value == "00") {
      getGroup(data).then((res: any) => {
        setData(res.data.data.data.map((item: any) => {
          item.key = item.group_id
          return item
        }))
      })
    }
  };
  const onSecondCityChange = (value: any) => {
    const index = cityData.findIndex((item) => { return item.code == value })
    setCityItem(value)
    setAreaData(cityData[index].children)
    setAreaItem(cityData[index].children[0].name)
    setWen(cityData[index].children[0].name)
  };
  const onAreaChange = (value: any) => {
    const index = areaData.findIndex((item) => { return item.code == value })
    setWen(areaData[index].name)
    setAreaItem(value)
  }

  // 查询事件
  const chaBtn = async () => {
    let res = await getGroup({ house_name: searchVal, group_status: statusVal, county: wen })
    // console.log(res)
    if (res.data.code === 1) {
      message.success('查询成功')
      setData(res.data.data.data.map((item: any) => {
        item.key = item.group_id
        return item
      }))
    } else {
      setData(res.data.data.data)
      message.error("没有要查询的数据")
    }
  }
  // 搜索框内容
  const inpValue = (e: any) => {
    if (e.target.value == "") {
      getGroup(data).then((res: any) => {
        setData(res.data.data.data)
      })
    }
    setSearchVal(e.target.value)
  }

  const columns: TableProps<any>['columns'] = [
    {
      title: '序号',
      dataIndex: 'group_id',
      key: 'group_id',
      render: (text) => <div style={{ width: 100 }}>{text}</div>,
    },
    {
      title: '图片',
      dataIndex: 'img',
      key: 'img',
      render: (text) => <img src={text} alt="" style={{ width: 80 }} />,
    },
    {
      title: '楼盘名称',
      dataIndex: 'house_name',
      key: 'house_name',
    },
    {
      title: '楼盘地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '发起人',
      dataIndex: 'initiator',
      key: 'initiator',
    },
    {
      title: '起始时间',
      dataIndex: 'start_time',
      key: 'start_time',
    },
    {
      title: '团购状态',
      dataIndex: 'group_status',
      key: 'group_status',
      render: (_, record) => {
        if (record.group_status == 0) {
          return <div>未开团</div>
        } else if (record.group_status == 1) {
          return <div>报名中</div>
        } else if (record.group_status == 2) {
          return <div>已开团</div>
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        if (record.status == 0) {
          return <Switch checkedChildren="正常" unCheckedChildren="关闭" onChange={
            () => {
              updateGroup({ id: record.group_id, status: 1 }).then((res: any) => {
                message.success(res.data.message)
              })
              getGroup(data).then((res: any) => {
                setData(res.data.data.data.map((item: any) => {
                  item.key = item.group_id
                  return item
                }))
              })
            }} />
        } else if (record.status == 1) {
          return <Switch checkedChildren="正常" unCheckedChildren="关闭" onChange={() => {
            updateGroup({ id: record.group_id, status: 0 }).then((res: any) => {
              message.success(res.data.message)
            })
            getGroup(data).then((res: any) => {
              setData(res.data.data.data.map((item: any) => {
                item.key = item.group_id
                return item
              }))
            })
          }} defaultChecked />
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (record) => (
        <Space size="middle">
          <Popconfirm
            // title="Delete the task"
            title={undefined}
            description="确认删除吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="是"
            cancelText="否"           >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 删除团购数据
  const confirm = async (data: any) => {
    let res = await delGroup(data.group_id)
    message.success(res.data.message)
    let res2 = await getGroup([])
    let groupData = res2.data.data.data
    groupData.map((item: any) => {
      item.key = item.group_id
      return item
    })
    setData(groupData)
  };
  const cancel = () => {
    message.error('取消删除');
  };

  return (
    <div>
      <p>团购管理</p>
      <div>
        <Space>
          搜索<Input onChange={inpValue} placeholder='团购名称' />
          状态
          <Select
            defaultValue="请选择"
            style={{ width: 120 }}
            onChange={handleChange}
            options={[
              { value: '请选择', label: '请选择' },
              { value: '0', label: '未开团' },
              { value: '1', label: '报名中' },
              { value: '2', label: '已开团' },
            ]}
          />
          {/* 三级联动 */}
          <Select
            defaultValue={city[0].code}
            style={{ width: 130 }}
            onChange={handleProvinceChange}
            options={provinceData.map((province) => ({ label: province.name, value: province.code }))}
          />
          <Select
            style={{ width: 130 }}
            value={cityItem}
            onChange={onSecondCityChange}
            options={cityData.map((city) => ({ label: city.name, value: city.code }))}
          />
          <Select
            style={{ width: 130 }}
            value={areaItem}
            onChange={onAreaChange}
            options={areaData.map((area) => ({ label: area.name, value: area.code }))}
          />
          <Button type='primary' onClick={chaBtn} disabled={wen.length || searchVal.length || statusVal.length ? false : true}>查询</Button>
        </Space>
      </div>

      <Table columns={columns} dataSource={data}
        pagination={false} scroll={{ x: 800, y: 400 }} />
    </div>
  )
}

export default Hoc_login(Index)
